import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/utils/auth'

// let baseURL = 'http://127.0.0.1:8080'
// let baseURL = 'http://192.168.0.45:8080'

const baseURL = 'http://121.196.181.151:8091'

// if (process.env.NODE_ENV !== 'development') {
//   baseURL = process.env.VUE_APP_BASE_API
// }

const service = axios.create({
  baseURL: baseURL
  // timeout: 10000
})

service.interceptors.request.use(config => {
  if (store.getters.token) {
    config.headers['X-Token'] = getToken()
    if (config.method === 'post' || config.method === 'put') {
      // 服务端从url中获取token
      if (config.url.indexOf('?') !== -1) {
        config.url = config.url + '&token=' + getToken()
      } else {
        config.url = config.url + '?token=' + getToken()
      }
    } else if (config.method === 'get' || config.method === 'delete') {
      config.params = {
        token: getToken(),
        ...config.params
      }
    }
  }
  return config
},
error => {
  return Promise.reject(error)
}
)

service.interceptors.response.use(response => {
  // 未设置状态码则默认成功状态
  const code = response.data.code || 200
  const res = response.data
  if (code === 401) {
    MessageBox.confirm(
      '登录状态已过期，您可以继续留在该页面，或者重新登录',
      '系统提示',
      {
        confirmButtonText: '重新登录',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      removeToken()
      location.reload() // 为了重新实例化vue-router对象 避免bug
    })
  }
  if (code !== 200 && code !== 0) {
    Message({
      message: res.msg || 'Error',
      type: 'error',
      duration: 2 * 1000
    })

    // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
    if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
      // to re-login
      MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
        confirmButtonText: 'Re-Login',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        store.dispatch('user/resetToken').then(() => {
          location.reload()
        })
      })
    }
    return Promise.reject(new Error(res.msg || 'Error'))
  } else {
    if (response.headers['content-disposition']) {
      return response
    }
    return res
  }
},
error => {
  Message({
    // message: error.message,
    message: '服务器异常',
    type: 'error'
  })
  return Promise.reject(error)
}
)
export { baseURL }
export default service
